﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhotoGalleryEnteties;
using PhotogalleryModel;

namespace photogalleryMVC.Controllers
{
	public static class OnPageElements
	{
        
        /// <summary>
        /// extension method for getting items quantity on page from  cookie 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cookieName"></param>
        /// <returns>Select list. Selected value is item quantity on page. Whether cookie is empty returns default value </returns>
        public static SelectList GetItemsOnPage(this HttpRequestBase request ,string cookieName, out int? selectedValue)
        {
           
            List<string> result = new List<string>() {"all","20", "50", "100"};
            selectedValue =null;
            if(request.Cookies.AllKeys.Contains(cookieName))
            {
                var cookieValue = request.Cookies.Get(cookieName ).Value;
                if (result.Contains(cookieValue))
                {
                    try
                    {
                        selectedValue = int.Parse(cookieValue );
                    }
                    catch{}
                    
                }
            }
            int value = 0;
            var list = from n in result
                       select new {Text = n, Value =  int.TryParse(n, out value) ? (int?)value : null};


            return new SelectList(list, "Value", "Text", selectedValue);
        }


        /// <summary>
        /// extension method for setting pagination cookie. If input value - null cookie is marked to delete
        /// </summary>
        /// <param name="context"> current http context </param>
        /// <param name="cookieName"></param>
        /// <param name="onPage">num of elements on page </param>
        public static  void SetPaginationCookie(this HttpContextBase context ,string cookieName,int? onPage)
        {
            var response = context.Response ;
            var request = context.Request;
            if (onPage == null)
            {
                if (request.Cookies.AllKeys.Contains(cookieName))
                    response.Cookies.Add(new HttpCookie(cookieName) { Expires = DateTime.Now.AddDays(-1d) });

            }
            else
            {
                response.Cookies .Add(new HttpCookie(cookieName , onPage.Value.ToString()));
            }
        }
	}
}